#!/usr/bin/env python
#coding:utf-8
#
# Copyright 2010 Close To U.
#
# Author:Darcy<http://closetou.com>
#

import os
import logging
import datetime
import time
from settings import *
from models import *
from paginator import Pagination
from google.appengine.api import users, images, urlfetch
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util, template

DEBUG = True

class BaseRequestHandler(webapp.RequestHandler):
  def generate(self, template_name, template_values={}):
    values = {
      'request': self.request,
      'user': users.get_current_user(),
      'is_admin':users.is_current_user_admin(),
      'login_url': users.create_login_url(self.request.uri),
      'logout_url': users.create_logout_url('/'),
      'debug': self.request.get('debug'),
      'cdn_cache':CDN_CACHE,
      'cdn_host':CDN_HOST,
      'gae_app_id':GAE_APP_ID,
      'version':VERSION
    }    
    site_theme = 'default'
    values.update(template_values)
    directory = os.path.dirname(__file__)
    path = os.path.join(directory, 'templates', 'themes', 'default', template_name)
    self.response.out.write(template.render(path, values, debug=DEBUG))

class MainHandler(BaseRequestHandler):
  def get(self):   
    q = Blobs.all()
    q.order('-view_count')
    q.filter('deleted =',False)
    toprank = q.fetch(5)

    q = Blobs.all()
    q.order('view_count')
    q.filter('deleted =',False)
    lastrank = q.fetch(5)

    q = Blobs.all()
    q.order('-created_at')
    q.filter('deleted =',False)
    results = q.fetch(15)
    
    index = Accumulator.get_or_insert(key_name='Blobs', name='Blobs').counter
    page = Pagination(index)
    
    values = {'photos':results,
              'toprank':toprank,
              'lastrank':lastrank,
              'pagination':page.pagination
              }
    self.generate('main.html',values)

class PhotosHandler(BaseRequestHandler):
  def get(self):
    current = self.request.get('page')
    if not current:
      current = 1
    
    index = Accumulator.get_or_insert(key_name='Blobs', name='Blobs').counter
    page_size = 25
    if index == 0:
      index = 1
    page = Pagination(index,int(current),page_size)
    offset = page.pagination['start_index']-1
    last_cursor = None
    while offset >1000:
      q = Blobs.all()
      q.order('-created_at')
      q.filter('deleted =',False)
      q.fetch(1000)
      last_cursor = q.cursor()
      offset -= 1000
      
    q = Blobs.all()    
    q.order('-created_at')
    q.filter('deleted =',False)
    if last_cursor:
      q.with_cursor(last_cursor)    
    results = q.fetch(page_size, offset=offset)
      
    values = {'photos':results,
              'pagination':page.pagination
              }
    self.generate('photos.html',values)

class PhotoHandler(BaseRequestHandler):
  def get(self,img_id):
    photo = Blobs.getbyid(img_id)      
    values = {'photo':photo}
    self.generate('photo.html',values)
    
class PhotoviewHandler(BaseRequestHandler):
  def get(self,img_id):
    p = Blobs.getbyid(img_id)
    if p:
      new_image = p.blob
      p.view_count +=1
      p.put()
      image = images.Image(new_image)
      directory = os.path.dirname(__file__)
      path = os.path.join(directory, 'templates', 'watermark.png')
      f = open(path,'rb')
      x = f.read()
      f.close()
      new_image = images.composite([(new_image, 0 ,0, 1.0, images.TOP_LEFT),
                                    (x, 0 ,0, 0.8, images.BOTTOM_LEFT)],
                                   image.width,image.height,0, images.PNG)

      self.response.headers['Content-Type'] = 'image/png'
      self.response.out.write(new_image)
    else: 
      self.error(404)

class ThumbnailHandler(BaseRequestHandler):
  def get(self,img_id,size):
    p = Blobs.getbyid(img_id)
    if p:
      size = int(size)
      MIN_SIZE = size
      if size > 200:
        MIN_SIZE = 200 #MIN_SIZE = 200
      if size < 20:
        MIN_SIZE = 20
      image = images.Image(p.blob)
      width = image.width
      height = image.height
      if width>height:
        rate = width*1.0/height
      else:
        rate = height*1.0/width
      size = int(MIN_SIZE*rate+1)
        
      new_image = images.resize(p.blob, width=size, height=size, output_encoding=images.PNG)        
      image = images.Image(new_image)
      right_x = round(MIN_SIZE*1.0/image.width,5)
      if right_x>1:
        right_x = 1.0
      else:
        left_x = (1- right_x)/2
        right_x = right_x + left_x
      bottom_y = round(MIN_SIZE*1.0/image.height,5)
      if bottom_y >1:
        bottom_y = 1.0
      else:
        top_y = (1-bottom_y)/2
        bottom_y = bottom_y + top_y
      new_image = images.crop(new_image, left_x, top_y, right_x, bottom_y, output_encoding=images.PNG)
      
      if False:
        #result = urlfetch.fetch('http://images.google.com.hk/intl/zh-CN_cn/images/logos/images_logo.gif')
        image = images.Image(new_image)
        directory = os.path.dirname(__file__)
        path = os.path.join(directory, 'templates', 'watermark.jpg')
        f = open(path,'rb')
        x = f.read()
        f.close()
        new_image = images.composite([(new_image, 0 ,0, 1.0, images.TOP_LEFT),
                                      (x, 0 ,0, 0.8, images.BOTTOM_LEFT)],
                                     image.width,image.height,0, images.PNG)

      self.response.headers['Content-Type'] = 'image/png'
      self.response.out.write(new_image)
    else: 
      self.error(404)
    
class DefaultHandler(BaseRequestHandler):
  def get(self):
    values = {}
    self.generate('default.html',values)
    
class OopsHandler(webapp.RequestHandler):
  def get(self):
    self.error(404)
    self.response.out.write('Oops!')
    
def main():
  application = webapp.WSGIApplication([(r'/',MainHandler),
                                        (r'/photos',PhotosHandler),
                                        (r'/photo/([0-9]+)',PhotoHandler),
                                        (r'/photo/view/([0-9]+)',PhotoviewHandler),
                                        (r'/photo/thumbnail/([0-9]+)x([0-9]+).png',ThumbnailHandler),                                        
                                        (r'/.*', OopsHandler)],
                                       debug=True)
  util.run_wsgi_app(application)

if __name__ == '__main__':
  main()
